//
//  LJCMusicPlay.m
//  WZLProduct
//
//  Created by 陆静聪 on 16/3/19.
//  Copyright © 2016年 HaiTeng. All rights reserved.
//

#import "LJCMusicPlay.h"

@interface LJCMusicPlay ()

@property (nonatomic, retain) AVPlayerItem *item;



@end

@implementation LJCMusicPlay

+ (LJCMusicPlay *)shareMusicPlayer {
    static LJCMusicPlay *play = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        play = [[LJCMusicPlay alloc] init];
    });
    
    return play;
}


- (instancetype)init {
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endPlay:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
        
        
    }
    return self;
}

- (void)endPlay:(NSNotification *)notification {
    _endBlock();
}


- (void)setUrl:(NSString *)url {
    if (_url != url) {
        _url = url;
        
            [self addAvPlayerItem];
    

    } else {
        if (CMTimeGetSeconds(_item.duration) == CMTimeGetSeconds(_item.currentTime)) {
            [self addAvPlayerItem];
        }
    }
}

/** 添加磁盘 */
- (void)addAvPlayerItem {
    _item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:_url]];
    AVPlayer *play = [LJCMusicPlay shareMusicPlayer];
    [play replaceCurrentItemWithPlayerItem:_item];
    [[LJCMusicPlay shareMusicPlayer] play];
    _isPlay = NO;
    
    
}


- (void)onOrOff {
    if (_isPlay == YES) {
        [[LJCMusicPlay shareMusicPlayer] play];
    } else {
        [[LJCMusicPlay shareMusicPlayer] pause];
    }
    _isPlay = !_isPlay;
}


- (CGFloat)getDuration {
    return CMTimeGetSeconds(_item.duration);
}

- (CGFloat)getCurrentTime {

    return CMTimeGetSeconds(_item.currentTime);
}

- (void)timingOff:(CGFloat)delayTime {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[LJCMusicPlay shareMusicPlayer] pause];
        _isPlay = YES;
    });
    
}

@end
